
import 'package:flutter/material.dart';
import 'package:hive_ce/hive.dart';
import 'package:hive_demo/hive/model/chapter.dart';

import '../hive/hive_boxes.dart';
import '../hive/model/book.dart';

class InfoScreen extends StatefulWidget {
  const InfoScreen({super.key});

  @override
  State<InfoScreen> createState() => _InfoScreenState();
}

class _InfoScreenState extends State<InfoScreen> {
  late final Box book;
  late final Box chapter;

  _addInfo() async {
    // Add info to people box
    // 示例书籍 1
    final book1 = Book(
      id: 0,
      title: 'Flutter 入门指南',
      author: '张三',
      chapterIds: [0,1],
      lastRead: 0,
    );

    // // 示例书籍 2
    // final book2 = Book(
    //   id: 1,
    //   title: 'Dart 编程实战',
    //   author: '李四',
    //   chapterIds: [0,1],
    //   lastRead: 0,
    // );

    // 将书籍存入 Box
    // book.putAll({
    //   book1.id: book1,
    //   book2.id: book2,
    // });
    book.put(book1.id, book1);

    // 添加书籍 1 的章节
    final chapters1 = [
      Chapter(bookId: book1.id, title: '第一章：环境搭建', content: '...', id: 0),
      Chapter(bookId: book1.id, title: '第二章：Widget 基础', content: '...', id: 1),
    ];

    // // 添加书籍 2 的章节
    // final chapters2 = [
    //   Chapter(bookId: book2.id, title: 'Dart 语法精要', content: '...', id: 2),
    //   Chapter(bookId: book2.id, title: '异步编程', content: '...', id: 3),
    // ];

    // 批量存储章节
    // 批量存储章节
    for(int i=0;i<chapters1.length;i++){
      chapter.put(chapters1[i].id, chapters1[i]);
    }

    print('数据已成功存储');

  }

  _getInfo() {
    // Get info from box
    print('书籍列表: ${book.values.toList()}');
    print('章节列表: ${chapter.values.toList()}');
  }

  _updateInfo() {
    // Update info of box
  }

  _deleteInfo() {
    // Delete info from box
    book.delete(0);
    chapter.delete(0);
    chapter.delete(1);
  }

  @override
  void initState() {
    super.initState();
    book = Hive.box<Book>(bookBox);
    chapter = Hive.box<Chapter>(chapterBox);
  }

  @override
  void dispose() {
    // Closes all Hive boxes
    Hive.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('People Info'),
      ),
      body: Center(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            ElevatedButton(
              onPressed: _addInfo,
              child: Text('Add'),
            ),
            ElevatedButton(
              onPressed: _getInfo,
              child: Text('Get'),
            ),
            ElevatedButton(
              onPressed: _updateInfo,
              child: Text('Update'),
            ),
            ElevatedButton(
              onPressed: _deleteInfo,
              child: Text('Delete'),
            ),
          ],
        ),
      ),
    );
  }

}
